using Lzfy_His_Service.Models;
using Lzfy_His_Service.Repositories;

namespace Lzfy_His_Service.Services
{
    /// <summary>
    /// UUM用户服务实现
    /// </summary>
    public class UumUserService : IUumUserService
    {
        private readonly IUumUserRepository _uumUserRepository;
        private readonly ILogger<UumUserService> _logger;

        public UumUserService(
            IUumUserRepository uumUserRepository,
            ILogger<UumUserService> logger)
        {
            _uumUserRepository = uumUserRepository;
            _logger = logger;
        }

        /// <summary>
        /// 根据用户名查询UUM用户信息
        /// </summary>
        public async Task<UumUserQueryResponse> GetUserByUserNameAsync(string userName)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(userName))
                {
                    return new UumUserQueryResponse
                    {
                        Success = false,
                        Message = "用户名不能为空"
                    };
                }

                var user = await _uumUserRepository.GetUserByUserNameAsync(userName);
                
                if (user == null)
                {
                    return new UumUserQueryResponse
                    {
                        Success = false,
                        Message = "未找到指定用户名的用户信息"
                    };
                }

                return new UumUserQueryResponse
                {
                    Success = true,
                    Message = "查询成功",
                    Data = user
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "根据用户名查询UUM用户信息失败: UserName={UserName}", userName);
                return new UumUserQueryResponse
                {
                    Success = false,
                    Message = "查询用户信息时发生错误"
                };
            }
        }

        /// <summary>
        /// 根据用户ID查询UUM用户信息
        /// </summary>
        public async Task<UumUserQueryResponse> GetUserByIdAsync(int userId)
        {
            try
            {
                if (userId <= 0)
                {
                    return new UumUserQueryResponse
                    {
                        Success = false,
                        Message = "用户ID必须大于0"
                    };
                }

                var user = await _uumUserRepository.GetUserByIdAsync(userId);
                
                if (user == null)
                {
                    return new UumUserQueryResponse
                    {
                        Success = false,
                        Message = "未找到指定ID的用户信息"
                    };
                }

                return new UumUserQueryResponse
                {
                    Success = true,
                    Message = "查询成功",
                    Data = user
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "根据用户ID查询UUM用户信息失败: UserId={UserId}", userId);
                return new UumUserQueryResponse
                {
                    Success = false,
                    Message = "查询用户信息时发生错误"
                };
            }
        }

        /// <summary>
        /// 根据工号查询UUM用户信息
        /// </summary>
        public async Task<UumUserQueryResponse> GetUserByPeopleIdentifierAsync(string peopleIdentifier)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(peopleIdentifier))
                {
                    return new UumUserQueryResponse
                    {
                        Success = false,
                        Message = "工号不能为空"
                    };
                }

                var user = await _uumUserRepository.GetUserByPeopleIdentifierAsync(peopleIdentifier);
                
                if (user == null)
                {
                    return new UumUserQueryResponse
                    {
                        Success = false,
                        Message = "未找到指定工号的用户信息"
                    };
                }

                return new UumUserQueryResponse
                {
                    Success = true,
                    Message = "查询成功",
                    Data = user
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "根据工号查询UUM用户信息失败: PeopleIdentifier={PeopleIdentifier}", peopleIdentifier);
                return new UumUserQueryResponse
                {
                    Success = false,
                    Message = "查询用户信息时发生错误"
                };
            }
        }

        /// <summary>
        /// 检查用户名是否存在
        /// </summary>
        public async Task<bool> UserNameExistsAsync(string userName)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(userName))
                {
                    return false;
                }

                return await _uumUserRepository.UserNameExistsAsync(userName);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "检查用户名是否存在失败: UserName={UserName}", userName);
                return false;
            }
        }

        /// <summary>
        /// 根据用户名更新用户电话
        /// </summary>
        public async Task<UpdateUserPhoneResponse> UpdateUserPhoneAsync(string userName, string? userPhone)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(userName))
                {
                    return new UpdateUserPhoneResponse
                    {
                        Success = false,
                        Message = "用户名不能为空"
                    };
                }

                var result = await _uumUserRepository.UpdateUserPhoneAsync(userName, userPhone);
                
                if (result)
                {
                    return new UpdateUserPhoneResponse
                    {
                        Success = true,
                        Message = "用户电话更新成功"
                    };
                }
                else
                {
                    return new UpdateUserPhoneResponse
                    {
                        Success = false,
                        Message = "未找到指定用户或更新失败"
                    };
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新用户电话失败: UserName={UserName}, UserPhone={UserPhone}", userName, userPhone);
                return new UpdateUserPhoneResponse
                {
                    Success = false,
                    Message = "更新用户电话时发生错误"
                };
            }
        }

        /// <summary>
        /// 根据用户名查询用户电话
        /// </summary>
        public async Task<GetUserPhoneResponse> GetUserPhoneAsync(string userName)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(userName))
                {
                    return new GetUserPhoneResponse
                    {
                        Success = false,
                        Message = "用户名不能为空"
                    };
                }

                var userPhone = await _uumUserRepository.GetUserPhoneAsync(userName);
                
                return new GetUserPhoneResponse
                {
                    Success = true,
                    Message = "查询成功",
                    UserPhone = userPhone
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询用户电话失败: UserName={UserName}", userName);
                return new GetUserPhoneResponse
                {
                    Success = false,
                    Message = "查询用户电话时发生错误"
                };
            }
        }

        /// <summary>
        /// 根据用户名更新退费任务数量
        /// </summary>
        public async Task<UpdateTaskAmountResponse> UpdateTaskAmountAsync(string userName, int taskAmount)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(userName))
                {
                    return new UpdateTaskAmountResponse
                    {
                        Success = false,
                        Message = "用户名不能为空"
                    };
                }

                var result = await _uumUserRepository.UpdateTaskAmountAsync(userName, taskAmount);
                
                if (result)
                {
                    return new UpdateTaskAmountResponse
                    {
                        Success = true,
                        Message = "退费任务数量更新成功"
                    };
                }
                else
                {
                    return new UpdateTaskAmountResponse
                    {
                        Success = false,
                        Message = "未找到指定用户或更新失败"
                    };
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新退费任务数量失败: UserName={UserName}, TaskAmount={TaskAmount}", userName, taskAmount);
                return new UpdateTaskAmountResponse
                {
                    Success = false,
                    Message = "更新退费任务数量时发生错误"
                };
            }
        }

        /// <summary>
        /// 根据用户名查询退费任务数量
        /// </summary>
        public async Task<GetTaskAmountResponse> GetTaskAmountAsync(string userName)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(userName))
                {
                    return new GetTaskAmountResponse
                    {
                        Success = false,
                        Message = "用户名不能为空"
                    };
                }

                var taskAmount = await _uumUserRepository.GetTaskAmountAsync(userName);
                
                return new GetTaskAmountResponse
                {
                    Success = true,
                    Message = "查询成功",
                    TaskAmount = taskAmount
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询退费任务数量失败: UserName={UserName}", userName);
                return new GetTaskAmountResponse
                {
                    Success = false,
                    Message = "查询退费任务数量时发生错误"
                };
            }
        }

        /// <summary>
        /// 批量更新授权码：将id_no字段不为空的数据，截取id_no的后四位，加上@再加上user_name，存入auth_code字段
        /// </summary>
        public async Task<BatchUpdateAuthCodeResponse> BatchUpdateAuthCodeAsync()
        {
            try
            {
                var (updatedCount, totalCount) = await _uumUserRepository.BatchUpdateAuthCodeAsync();
                
                return new BatchUpdateAuthCodeResponse
                {
                    Success = true,
                    Message = $"批量更新授权码成功，共处理{totalCount}条记录，成功更新{updatedCount}条记录",
                    UpdatedCount = updatedCount,
                    TotalCount = totalCount
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量更新授权码失败");
                return new BatchUpdateAuthCodeResponse
                {
                    Success = false,
                    Message = "批量更新授权码时发生错误",
                    UpdatedCount = 0,
                    TotalCount = 0
                };
            }
        }
    }
}